#!/usr/bin/python
import sqlite3
import os
import cgi
import cgitb
from pygallib import usersession
from pygallib import layoutlib
from pygallib import albumlib

cgitb.enable()
logged_in = usersession.logged_in()

headers = {}
headers["Content-type"] = "text/html"
layoutlib.print_http_headers(headers)
layoutlib.print_page_open("PyGallery - Home")
print("<body>")
menu = []
menu.append(("Home", "gallery.cgi"))

user = None
user_root = False
if logged_in:
  user = usersession.get_session_user()
  if user["root"] == 1:
    user_root = True

layoutlib.print_page_header(menu, user)

print('<div id="page_body">')
# Display all albums
(cur, conn) = albumlib.get_albums()
print('<ul id="gallery_albums">')
for album in cur:
  # Skip if the album is private and 
  # doesn't belong to logged in user
  # and user isn't root (he gets to see everything)
  if int(album["is_public"]) == 0: 
    if logged_in:
      if int(album["user_id"]) != int(user["user_id"]) and not user_root:
        continue
    else:
      continue
  # Select one picture to display for album
  picture = albumlib.get_album_preview(album["album_id"])
  album_url = "album.cgi?id=%d" % album["album_id"]
  if picture is None:
    image_url = '/PictureShare/images/no_image.png'
  else:
    image_url = '/PictureShare/users/%s/%s/%s' % \
        (album["username"], 
         "albumthumb"+str(album["album_id"]), 
         picture["file_name"])
  print('<li>')
  print('<a href="%s"><img src="%s" height="150" /></a>' 
      % (album_url, image_url))
  print('<a href="%s">%s</a>' % 
      (album_url, album["name"])) 
  print('<p class="username">%s</p>' % album["username"])
  print('</li>')
conn.close()
print('</ul>')
print('</div>') # end page_body
layoutlib.print_page_close()
